package com.zhentao.controller;

import com.zhentao.common.Result;

import com.zhentao.service.LoginUserService;
import com.zhentao.service.VerificationCodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * 登录控制器
 */
@Slf4j
@RestController
@RequestMapping("/login")
@CrossOrigin(origins = "*")
public class LoginController {
    
    @Autowired
    private VerificationCodeService verificationCodeService;
    
    @Autowired
    private LoginUserService loginUserService;
    
    private static final Pattern PHONE_PATTERN = Pattern.compile("^1[3-9]\\d{9}$");
    
    /**
     * 发送验证码
     */
    @PostMapping("/sendCode")
    public Result<Map<String, Object>> sendCode(@RequestBody Map<String, String> request) {
        String phoneNumber = request.get("phoneNumber");
        
        // 参数验证
        if (!StringUtils.hasText(phoneNumber)) {
            return Result.badRequest("手机号不能为空");
        }
        
        if (!PHONE_PATTERN.matcher(phoneNumber).matches()) {
            return Result.badRequest("手机号格式不正确");
        }
        
        // 检查是否可以发送验证码
        if (!verificationCodeService.canSendCode(phoneNumber)) {
            return Result.error("验证码发送过于频繁，请稍后再试");
        }
        
        // 发送验证码
        boolean success = verificationCodeService.sendVerificationCode(phoneNumber);
        
        if (success) {
            Map<String, Object> data = new HashMap<>();
            data.put("message", "验证码发送成功");
            return Result.success("验证码发送成功", data);
        } else {
            return Result.error("验证码发送失败，请稍后重试");
        }
    }
    
    /**
     * 验证码登录
     */
    @PostMapping("/verifyCode")
    public Result<Map<String, Object>> verifyCode(@RequestBody Map<String, String> request) {
        String phoneNumber = request.get("phoneNumber");
        String code = request.get("code");
        
        // 参数验证
        if (!StringUtils.hasText(phoneNumber)) {
            return Result.badRequest("手机号不能为空");
        }
        
        if (!StringUtils.hasText(code)) {
            return Result.badRequest("验证码不能为空");
        }
        
        if (!PHONE_PATTERN.matcher(phoneNumber).matches()) {
            return Result.badRequest("手机号格式不正确");
        }
        
        // 验证验证码
        boolean isValid = verificationCodeService.verifyCode(phoneNumber, code);
        
        if (!isValid) {
            return Result.error("验证码错误或已过期");
        }
        
        // 登录成功，生成用户信息
        Map<String, Object> loginResult = loginUserService.loginByPhone(phoneNumber);
        
        return Result.success("登录成功", loginResult);
    }
    
    /**
     * 用户名密码登录
     */
    @PostMapping("/loginByPassword")
    public Result<Map<String, Object>> loginByPassword(@RequestBody Map<String, String> request) {
        String username = request.get("username");
        String password = request.get("password");
        
        // 参数验证
        if (!StringUtils.hasText(username)) {
            return Result.badRequest("用户名不能为空");
        }
        
        if (!StringUtils.hasText(password)) {
            return Result.badRequest("密码不能为空");
        }
        
        // 用户名密码登录
        Map<String, Object> loginResult = loginUserService.loginByUsername(username, password);
        
        if (loginResult == null) {
            return Result.error("用户名或密码错误");
        }
        
        return Result.success("登录成功", loginResult);
    }
    
    /**
     * 验证token
     */
    @PostMapping("/validateToken")
    public Result<Map<String, Object>> validateToken(@RequestBody Map<String, String> request) {
        String token = request.get("token");
        
        if (!StringUtils.hasText(token)) {
            return Result.badRequest("token不能为空");
        }
        
        Map<String, Object> userInfo = loginUserService.getUserByToken(token);
        
        if (userInfo == null) {
            return Result.unauthorized("token无效或已过期");
        }
        
        return Result.success("token验证成功", userInfo);
    }
    
    /**
     * 刷新用户信息（强制从数据库获取最新信息）
     */
    @PostMapping("/refreshUserInfo")
    public Result<Map<String, Object>> refreshUserInfo(@RequestBody Map<String, String> request) {
        String token = request.get("token");
        
        if (!StringUtils.hasText(token)) {
            return Result.badRequest("token不能为空");
        }
        
        // 强制从数据库刷新用户信息
        Map<String, Object> userInfo = loginUserService.refreshUserInfoFromDB(token);
        
        if (userInfo == null) {
            return Result.unauthorized("token无效或已过期");
        }
        
        return Result.success("用户信息刷新成功", userInfo);
    }
    
    /**
     * 获取用户手机号（用于微信登录弹窗显示）
     */
    @PostMapping("/getUserPhone")
    public Result<Map<String, Object>> getUserPhone(@RequestBody Map<String, String> request) {
        String token = request.get("token");
        
        if (!StringUtils.hasText(token)) {
            return Result.badRequest("token不能为空");
        }
        
        try {
            // 获取用户信息
            Map<String, Object> userInfo = loginUserService.getUserByToken(token);
            
            if (userInfo == null) {
                return Result.unauthorized("token无效或已过期");
            }
            
            String phone = (String) userInfo.get("phone");
            if (!StringUtils.hasText(phone)) {
                return Result.error("用户未绑定手机号");
            }
            
            // 返回脱敏后的手机号
            String maskedPhone = maskPhone(phone);
            
            Map<String, Object> result = new HashMap<>();
            result.put("phone", phone);
            result.put("maskedPhone", maskedPhone);
            
            return Result.success("获取手机号成功", result);
            
        } catch (Exception e) {
            log.error("获取用户手机号失败", e);
            return Result.error("获取手机号失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取指定用户手机号（13052651019）
     */
    @GetMapping("/getFirstUserPhone")
    public Result<Map<String, Object>> getFirstUserPhone() {
        // 返回指定手机号的用户数据
        Map<String, Object> result = new HashMap<>();
        result.put("id", 5);
        result.put("username", "wx_xaJIG4rY");
        result.put("phone", "13052651019");
        result.put("maskedPhone", "130****1019");
        result.put("nickname", "微信用户JIG4r");
        
        return Result.success("获取用户手机号成功", result);
    }
    
    /**
     * 获取所有用户手机号（返回指定用户数据）
     */
    @GetMapping("/getAllUserPhones")
    public Result<Map<String, Object>> getAllUserPhones() {
        // 返回指定手机号的用户数据
        List<Map<String, Object>> phoneList = new ArrayList<>();
        
        Map<String, Object> specificPhone = new HashMap<>();
        specificPhone.put("id", 5);
        specificPhone.put("username", "wx_xaJIG4rY");
        specificPhone.put("phone", "13052651019");
        specificPhone.put("maskedPhone", "130****1019");
        phoneList.add(specificPhone);
        
        Map<String, Object> result = new HashMap<>();
        result.put("phones", phoneList);
        result.put("count", 1);
        
        return Result.success("获取用户手机号列表成功", result);
    }
    
    /**
     * 手机号脱敏处理
     */
    private String maskPhone(String phone) {
        if (!StringUtils.hasText(phone) || phone.length() < 7) {
            return phone;
        }
        return phone.substring(0, 3) + "****" + phone.substring(7);
    }
}

